package com.digiwin.middleware.service;

import com.digiwin.middleware.properties.DigiwinMiddlewareProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @Author yanggld
 * @Date 2020/2/14-17:15
 * @Description
 */
public class IamService {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private DigiwinMiddlewareProperties digiwinMiddlewareProperties;

	/**
	 * 产生accessToken
	 */
	public static String grantAccessUrl =  "/api/iam/v2/identity/token/grant/access";

	public String grantAccessToken(String userId,String tenantId){
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.setContentType(MediaType.APPLICATION_JSON);
		requestHeaders.add("digi-middleware-auth-app", digiwinMiddlewareProperties.getAppToken());
		HashMap<String, Object> map = new HashMap<>();
		map.put("grant_type","verifyUser_credentials");
		map.put("tenantId",tenantId);
		map.put("verifyUserId",userId);
		map.put("appId","escloud");
		HttpEntity requestEntity = new HttpEntity(map,requestHeaders);
		try {
			ResponseEntity<String> exchange = restTemplate.exchange(digiwinMiddlewareProperties.getIamAddress()+grantAccessUrl, HttpMethod.POST, requestEntity, String.class, new HashMap<>());
			String body = exchange.getBody();
			return body;
		} catch (Exception e) {
			String body = e.getMessage();
			return body;
		}
	}

}
